import json,random
from flask import Blueprint,request,jsonify,redirect
from application.models.users.user import *
from tools.myredis import r

course_blue = Blueprint("courseblue",__name__)

# 获取课程详情
@course_blue.route("/getDetail")
def getDetail():
    # 获取id
    id = request.args.get('id')
    userid = request.args.get('userid')
    # 查询课程信息
    course = Course.query.filter(Course.id==id).first()
    # 加入浏览记录，获取到userid
    if userid:
        key = 'collection'+str(userid)+'pro'+str(id)
        r.hash_add(key,'id',course.id)
        r.hash_add(key,'name',course.name)
    # 返回课程信息
    course = {"id":course.id,'name':course.name}
    return jsonify({
        "code":200,
        "course":course
    })


# 获取最近浏览
@course_blue.route('/getViews')
def getViews():
    # 获取id
    userid = request.args.get('userid')
    findkey = 'collection'+str(userid)+"*"
    gidlist = r.getvalues(findkey)
    reslist = []
    for i in gidlist:
        goods = r.getall_hash(i)
        dict = {}
        for k,v in goods.items():
            kk = k.decode()
            vv = v.decode()
            dict[kk] = vv
        reslist.append(dict)
    return jsonify({
        "code":200,
        "list":reslist
    })


# 加入购物车
@course_blue.route("/buy")
def buy():
    # 获取参数 userid courseid
    userid = request.args.get('userid')
    courseid = request.args.get('courseid')
    # 加减类型，默认为+
    type = 1
    try:
        type = request.args.get('type')
    except:
        pass
    # 从hash中获取数据，如果存在数量+1，
    key = 'buy' + str(userid)+'course'+str(courseid)
    # 如果不存在，存入redis hash
    flag = r.findkey_hash(key)
    print(flag)
    # 存在
    if flag:
        # 数量+1
        ff = r.jiajian_hash(key,'number',1,type)
        if ff == False:
            return jsonify({
                "code":10010,
                "mes":"不能再减"
            })
    else:
        r.hash_add(str(key),'id',courseid)
        r.hash_add(key,'number',1)
        # 选中
        r.hash_add(key, 'flag', True)
    # 返回结果
    return jsonify({
        "code":200,
        "mes":"加入成功"
    })


# 获取购物车
@course_blue.route('/mycart')
def mycart():
    # 获取参数userid
    userid = request.args.get('userid')
    # 从hash中获取商品id和数量
    key = 'buy'+str(userid)+"*"
    goods = r.getvalues(key)
    glist = []
    tmoney = 0
    tcount = 0
    if goods:
        for i in goods:
            # 获取每一条商品的具体信息
            good = r.getall_hash(i)
            rescourse = {}
            for k,v in good.items():
                params = k.decode()
                value = v.decode()
                if params == 'id':
                    # 获取到的商品信息
                    tcourse = Tcourse.query.filter(Tcourse.id == value).first()
                    rescourse['id'] = tcourse.id
                    rescourse['title'] = tcourse.title
                    rescourse['url'] = tcourse.url
                    rescourse['price'] = float(tcourse.price)
                if params == 'number':
                    # 获取购买的数量
                    rescourse['number'] = value
            rescourse['total'] = int(rescourse['price'])*int(rescourse['number'])
            # 计算总价
            tmoney = float(tmoney)+float(rescourse['total'])
            tcount = int(tcount)+int(rescourse['number'])
            glist.append(rescourse)
    # 价格，图片，名字等从mysql中获取，从redis商品缓存中读取
    # 数据重组返回
    return jsonify({
        "code":200,
        "glist":glist,
        "tmoney":tmoney,
        "tcount":tcount
    })


# from job.task.mytask import task_one_function
# @course_blue.route('/testabc')
# def testabc():
#     res = task_one_function.delay(12,13)
#     print(res)
#     return jsonify({"code":200})


# 修改单个选中
@course_blue.route('/modifyStatus', methods=['GET'])
def modifyStatus():
    # 接收参数 userid  goodsid
    userid = request.args.get('userid')
    cid = request.args.get('cid')
    # 获取过来的判断状态
    key = "buy"+str(userid)+"course"+str(cid)
    flag = r.getone_hash(key, "flag")
    # 设置默认为选中
    cflag = "True"
    # 如果true改为false，如果false改为true
    if flag:
        flag = flag.decode()
        # 根据返回结果选中相反的
        if flag == "True":
            cflag = "False"

        r.hash_add(key, "flag", cflag)
        return jsonify({"code": 200})

@course_blue.route("/modifyAllStatus")
def modifyAllStatus():
    userid = request.args.get('userid')
    status = request.args.get('status')
    flag = "false"
    if status == "true":
        flag = "True"
    # 把购物车全部修改为选中或者未选中
    keys = r.getvalues("buy"+str(userid)+"*")
    for i in keys:
        r.hash_add(i,'flag', flag)
    return jsonify({"code": 200})

# 生成订单
@course_blue.route('/create_order', methods=['POST'])
def create_order():
    # 接收参数 userid
    data = json.loads(request.data)
    userid = data["userid"]
    # 接口幂等性操作， 验证
    order_token = data["order_token"]
    value = r.str_get(order_token)
    print(value)
    if not value:
        return jsonify({"code":10010, "mes": "已经生成不能重复操作"})
    # 删除
    r.del_str(order_token)
    # 根据userid查询购物车
    key = "buy" + str(data['userid']) + "*"
    glist = r.getvalues(key)
    totalmoney = 0
    # 生成订单号
    order_on = str(random.randint(10,99))+str(data['userid'])
    # 判断购物车中已经选中的记录
    if glist:
        for i in glist:
            flag = r.getone_hash(i, 'flag')
            # 获取每一条商品的具体信息
            if flag:
                flag = flag.decode()
                # 根据返回结果
                if flag == "True":
                    # id 商品id
                    id = r.getone_hash(i,'id')
                    id = id.decode()
                    # 商品数量
                    number = r.getone_hash(i, 'number')
                    number = number.decode()
                    # 判断购物车中已经选中的记录
                    tcourse = Tcourse.query.filter(Tcourse.id == id).first()
                    # 查询训练营课程表, 判断库存
                    if int(tcourse.store) < int(number):
                        return jsonify({"code": 10010, "mes": "库存不足"})
                    # 写入订单详情表
                    tmoney = float(tcourse.price) * float(number)
                    detil = OrdersDetall(order_no=int(order_on), courseid=id, number=number, price=tcourse.price, tmoney=tmoney)
                    db.session.add(detil)
                    # 总价
                    totalmoney = float(totalmoney) + float(tmoney)
                    # 删除购物车已经选中的记录
                    r.del_str(i)

        # 写入订单表
        print(int(order_on))
        order = Orders(order_no=int(order_on), userid=userid, tmoney=totalmoney)
        db.session.add(order)
        db.session.commit()
        return jsonify({"code": 200, "orderno": order_on})

# 订单表展示
@course_blue.route("/orders")
def orders():
    # 获取参数 userid
    orderno = request.args.get('orderno')
    # 查询订单表
    order = Orders.query.filter(Orders.order_no == orderno).all()
    olist = [{
        "id": i.id,
        "orderno": i.order_no,
        "userid": i.userid,
        "tmoney": i.tmoney,
        "status": i.status,
    }
        for i in order]
    # 查询订单详情表
    orderdetall = OrdersDetall.query.filter(OrdersDetall.order_no == orderno).all()
    clist = [{
        "id": i.id,
        "orderno": i.order_no,
        "courseid": i.courseid,
        "number": i.number,
        "price": i.price,
        "tmoney": i.tmoney,
    } for i in orderdetall]
    # 序列化返回
    return jsonify({"code": 200, "olist": olist, "clist": clist})
import uuid
@course_blue.route("get_order_token")
def get_order_token():
    # 生成token
    token = uuid.uuid1().hex
    # 将token存入redisf
    r.str_add(token, "1")
    # 返回结果
    return jsonify({"token": token, "code": 200})


# 接口幂等性操作
import uuid
@course_blue.route("get_order_token")
def get_order_token():
    # 生成token
    token = uuid.uuid1().hex
    # 将token存入redisf
    r.str_add(token, "1")
    # 返回结果
    return jsonify({"token": token, "code": 200})
from application.tools.comm import get_ali_object
# 订单表支付
@course_blue.route("/pay_order", methods=['GET'])
def pay_order():
    # 获取参数
    order_no = request.args.get('order_no')
    # 通过订单号查询价格
    order = Orders.query.filter(Orders.order_no == order_no).first()
    # 支付， 返回支付url
    # 生成支付的url
    pay = get_ali_object()

    # 订单号重构充值1 支付订单2
    orders = str(order_no)+':'+str(2)
    query_params = pay.direct_pay(
        subject="test",  # 商品简单描述
        out_trade_no=str(orders),  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=float(order.tmoney),  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({"code": 200, "url": pay_url})

# 课程章节选择课程添加
@course_blue.route("/get_course", methods=['GET'])
def add_chapter():
    # 获取全部课程
    course = Course.query.all()
    # 课程章节列表
    list = []
    for i in course:
        dict = {"id": i.id, "name": i.name}
        list.append(dict)
    return jsonify({"code": 200, "list": list})

import os
# 保存图片到本地
@course_blue.route("/upload", methods=["POST"])
def upload():
    # 获取文件
    file = request.files.get('file')
    # 获取文件名
    filename = file.filename
    path = os.path.join("upload/media/"+filename)
    # 保存文件
    file.save(path)
    # 通过id获取到数据， url
    # 用url接收数据库中的url
    # remove加上数据库中的url就可以直接删除
    # 删除文件
    # os.remove(url)

    return jsonify({"code": 200, "url": path})

# 添加课程章节杰克
@course_blue.route("/addjie", methods=["POST"])
def addjie():
    # 获取参数
    data = json.loads(request.data)
    if not data:
        return jsonify({"code": 10010, "mes": "参数错误"})
    # 添加课程章节
    name = data['name']
    url = data['url']
    tcount = data['tcount']
    courseid = data['courseid']
    try:
        jie = Jie(name=name, url=url, tcount=tcount, courseid=courseid)
        db.session.add(jie)
        db.session.commit()
    except Exception as e:
        print(e)
        return jsonify({"code": 10010, "mes": "章节添加失败"})
    return jsonify({"code": 200, "mes": "章节添加成功"})

# # 老师的信息
# @course_blue.route("/teacher_info", methods=["GET"])
# def teacher_info():
#     # 获取参数
#     course_id = request.args.get("course_id")
#     # 查询课程表
#     sql = "SELECT * from teacher where"
#     list = []
#     print("-----------------------------", tcharts)
#     return jsonify({"code": 200})